// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;

namespace SnapObjects.Data
{
    internal class RawBuildStatement : SqlBuildStatement
    {
        private string _sqlRaw;
        public RawBuildStatement(SqlStatementType statementType = SqlStatementType.SqlRaw)
        {
            this.StatementType = statementType;
        }

        public RawBuildStatement(string sqlRaw, SqlStatementType statementType = SqlStatementType.SqlRaw)
        {
            _sqlRaw = sqlRaw;
            this.StatementType = statementType;
        }

        internal RawBuildStatement(bool igoreSyntaxType)
        {
            this.StatementType = SqlStatementType.SqlRaw;

            this.IgnoreSyntaxType = true;
        }

        public override SqlStatementType StatementType { get; }

        private bool IgnoreSyntaxType { get; }

        public SqlStatementType SyntaxType
        {
            get
            {
                if (this.IgnoreSyntaxType || this.StatementType == SqlStatementType.Procedure)
                {
                    return this.StatementType;
                }

                return this.GetSyntaxType(this.SqlRaw);
            }
        }

        public string SqlRaw
        {
            get => _sqlRaw;
            set
            {
                this.OnChanged(null);

                _sqlRaw = value;
            }
        }

        private SqlStatementType GetSyntaxType(string sqlRaw)
        {
            var raw = sqlRaw.Trim();

            if (raw.StartsWith("select", StringComparison.OrdinalIgnoreCase))
            {
                return SqlStatementType.Select;
            }
            else if (raw.StartsWith("insert", StringComparison.OrdinalIgnoreCase))
            {
                return SqlStatementType.Insert;
            }
            else if (raw.StartsWith("update", StringComparison.OrdinalIgnoreCase))
            {
                return SqlStatementType.Update;
            }
            else if (raw.StartsWith("delete", StringComparison.OrdinalIgnoreCase))
            {
                return SqlStatementType.Delete;
            }
            else
            {
                return SqlStatementType.SqlRaw;
            }
        }

        public override SqlBuildStatement Clone()
        {
            return new RawBuildStatement(this.SqlRaw);
        }
    }
}
